import { ref, computed } from "vue";

export function useEditTodo(todosRef) {
    const editingTodoRef = ref(null)
    let todoCache = null
    const editingHandle = (todo) => {
        todoCache = todo.title
        editingTodoRef.value = todo
    }

    const confirmEdit = () => {
        editingTodoRef.value = null
    }

    const cancelEdit = (todo) => {
        editingTodoRef.value = null
        todo.title = todoCache
    }

    const allDoneRef = computed(() => {
        const val = todosRef.value.filter((todo) => !todo.completed).length === 0
        return val
    })

    const setAllChecked = (checked) => {
        todosRef.value.forEach((todo) => {
            todo.completed = checked
        })
    }

    return {
        editingHandle,
        editingTodoRef,
        confirmEdit,
        cancelEdit,
        allDoneRef,
        setAllChecked
    }
}